package com.qing.microservices.eureka.consumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author guoqf
 * @date 2021/4/1 13:34
 */
@RestController
public class HelloController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    private String serviceName = "eureka-provider";

    @GetMapping("/info")
    public String getInfo() {
        List<String> services = discoveryClient.getServices();
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        StringBuilder sb = new StringBuilder();
        sb.append("Services: [").append(services).append("]<br/>");
        sb.append("Instances: [<br/>");
        instances.forEach(instance -> {
            sb.append("    ").append(instance.getHost()).append(" : ").append(instance.getPort()).append("<br/>");
        });
        sb.append("]<br/>");
        return sb.toString();
    }

    @GetMapping("/hello")
    public String sayHello(@RequestParam("name") String name) {
        ServiceInstance serviceInstance = discoveryClient.getInstances(serviceName).stream().findAny().orElseThrow(() -> new IllegalStateException("No avail intance for service[" + serviceName + "] found"));
        return restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/echo?name=" + name, String.class);
    }
}
